<?php

namespace console\controllers;

use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use common\models\WxGh;
use common\models\MktUser;

class WxUserController extends \yii\console\Controller {

    public function actionSync($gh_id=WxGh::DEFAULT_GH_ID) {
        $gh = WxGh::findOne(['gh_id' => $gh_id]);                
        $wxapp = $gh->loadWx()->getApplication();
        $responseArray = $wxapp->user->lists()->toArray();       
        $total = $responseArray['total'];
        echo "Totally {$total} weixin users.".PHP_EOL;

        $count = $responseArray['count'];
        if (!empty($count)) {
            $this->syncOpenids($gh, $responseArray['data']['openid']);
        }
        while ($count < $total && !empty($responseArray['next_openid'])) {
            echo "processing {$responseArray['count']} ending with {$count}.".PHP_EOL;
            $responseArray = $wxapp->user->lists($responseArray['next_openid'])->toArray();
            if (!empty($responseArray['count']))
                $this->syncOpenids($gh, $responseArray['data']['openid']);
            else
                break;
            $count += $responseArray['count'];
        }
    }

    private function syncOpenids($gh, array $openid_list) {
        foreach ($openid_list as $openid) {
            $wxUser = MktUser::findOne([
                        'openid' => $openid,
            ]);
            if (empty($wxUser)) {
                $wxUser = $gh->getWxUser($openid);
                //$wxUser->updateAttributes([
                //    'created_at' => $wxUser->subscribe_time,
                //]);
            } else {
                $wxUser = $gh->getWxUser($openid);
            }
        }
    }


}
